<?php
namespace Home\Controller;
use Think\Controller;
use Home\Model\IndexModel;
class IndexController extends Controller {
    public function __construct(){
		 parent::__construct();
		// $this->chlCats = getChannelCats();
	}

	public function index(){
		//获得参数 signature nonce token timestamp echostr
		$nonce     = $_GET['nonce'];
		$token     = 'wechat';
		$timestamp = $_GET['timestamp'];
		$echostr   = $_GET['echostr'];
		$signature = $_GET['signature'];
		//形成数组，然后按字典序排序
		$array = array();
		$array = array($nonce, $timestamp, $token);
		sort($array);
		//拼接成字符串,sha1加密 ，然后与signature进行校验
		$str = sha1( implode( $array ) );
		if( $str  == $signature && $echostr ){
			//第一次接入weixin api接口的时候
			echo  $echostr;
			exit;
		}else{
			$this->reponseMsg();
		}
	}
	// 接收事件推送并回复
	public function reponseMsg(){
		//1.获取到微信推送过来post数据（xml格式）
		$postArr = $GLOBALS['HTTP_RAW_POST_DATA'];
		//2.处理消息类型，并设置回复类型和内容
		
		$postObj = simplexml_load_string( $postArr );
		
		//判断该数据包是否是订阅的事件推送
		if( strtolower( $postObj->MsgType) == 'event'){
			//如果是关注 subscribe 事件
			if( strtolower($postObj->Event == 'subscribe') ){
				//回复用户消息(纯文本格式)	
				$content  = '欢迎关注我们的微信公众账号'.$postObj->FromUserName.'-'.$postObj->ToUserName;
				$indexModel = new IndexModel();
				$indexModel->responseSubscribe($postObj,$content);	

			}
		}

		
		//用户发送tuwen1关键字的时候，回复一个单图文
		if( strtolower($postObj->MsgType) == 'text' && trim($postObj->Content)=='tuwen1' ){
			//从数据库查询得到，组装为数组
			$arr = array(
				array(
					'title'=>'imooc',
					'description'=>"imooc is very cool",
					'picUrl'=>'http://www.imooc.com/static/img/common/logo.png',
					'url'=>'http://www.imooc.com',
				),
				array(
					'title'=>'hao123',
					'description'=>"hao123 is very cool",
					'picUrl'=>'https://www.baidu.com/img/bdlogo.png',
					'url'=>'http://www.hao123.com',
				),
				array(
					'title'=>'qq',
					'description'=>"qq is very cool",
					'picUrl'=>'http://www.imooc.com/static/img/common/logo.png',
					'url'=>'http://www.qq.com',
				),
			);

			$indexModel = new IndexModel();
			$indexModel->responseNews($postObj,$arr);
			

			//注意：进行多图文发送时，子图文个数不能超过10个
		}else{
			// switch( trim($postObj->Content) ){
			// 	case 1:
			// 		$content = '您输入的数字是1';
			// 	break;
			// 	case 2:
			// 		$content = '您输入的数字是2';
			// 	break;
			// 	case 3:
			// 		$content = '您输入的数字是3';
			// 	break;
			// 	case 4:
			// 		$content = "<a href='http://www.imooc.com'>慕课</a>";
			// 	break;
			// 	case '英文':
			// 		$content = 'imooc is ok';
			// 	break;
			// }	
				
			//天气查询
			$ch = curl_init();
		    $url = 'http://apis.baidu.com/apistore/weatherservice/cityname?cityname='.urlencode( $postObj->Content );
		    $header = array(
		        'apikey: 2f2e496817d4bff0456a6df2c8385b59',
		    );
		    // 添加apikey到header
		    curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		    // 执行HTTP请求
		    curl_setopt($ch , CURLOPT_URL , $url);
		    $res = curl_exec($ch);
		    $arr = json_decode($res,true);
		    $content=$arr['retData']['city'].'天气如下:'.$arr['retData']['weather'];

		    $indexModel = new IndexModel();
			$indexModel->responseText($postObj,$content);
			
		}//if end
	}//reponseMsg end


		/***
		*
		*
		**/
	function http_curl($url,$type='get',$res='json',$arr=''){
		//获取imooc
		//1.初始化curl
		$ch = curl_init();
		//2.设置curl的参数
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		if($type=='post'){
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
		}
		//3.采集
		$output = curl_exec($ch);
		//4.关闭
		curl_close($ch);
		if( curl_errno($ch) ){
	 		var_dump( curl_error($ch) );
	 	}
		if($res=='json'){
			//不加true则返回对象
			return json_decode($output,true);
		}
		
	}

	public function hello(){
		echo 'hello';
	}

	// public function getWxAccessToken(){
	// 	//1.请求url地址
	// 	$appid = 'wxa1079056cc3abb29';
	// 	$appsecret =  'cb04027ffbf37287bb46fcbade44771d';
	// 	$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
	// 	//2初始化
	// 	$ch = curl_init();
	// 	//3.设置参数
	// 	curl_setopt($ch , CURLOPT_URL, $url);
	// 	curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
	// 	//4.调用接口 
	// 	$res = curl_exec($ch);
	// 	//5.关闭curl
	// 	curl_close( $ch );
	// 	if( curl_errno($ch) ){
	// 		var_dump( curl_error($ch) );
	// 	}
	// 	$arr = json_decode($res, true);
	// 	var_dump( $arr );
	// }

	function getWxServerIp(){
		$accessToken = "gztOEMidizDRMU2sFJiQ3FkW180Xf5vCDzR75XB14BUuJjxPxM4xzxKIhiQqVNrxgV4MpAyhBxffhlO4Gn8ol2n1mjP1XDfrgWngspHBZgwNFKcADABTY";
		$url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$accessToken;
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		$res = curl_exec($ch);
		curl_close($ch);
		if(curl_errno($ch)){
			var_dump(curl_error($ch));
		}
		$arr = json_decode($res,true);
		echo "<pre>";
		var_dump( $arr );
		echo "</pre>";
	}

	// public function getWxAccessToken(){
	// 	if( $_SESSION['access_token'] && $_SESSION['expire_time']>time() ){
	// 		//var_dump($_SESSION['access_token']);
	// 		return $_SESSION['access_token'];
	// 	}else{
	// 		//access_token 过期，重新获取
	// 		$appid = 'wx486c0d836824ac89';
	// 		$appsecret =  '23224a1ca9cedf520cfade68118f1443';
	// 		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
	// 		$res = $this->http_curl($url,'get','json');
	// 		$access_token = $res['access_token'];
	// 		$_SESSION['access_token']=$access_token;
	// 		$_SESSION['expire_time']=time()+7000;
	// 		//var_dump($access_token);
	// 		return $access_token;
	// 	}
	// }

	public function defineItem(){
		header('content-type:text/html;charset=utf-8');
		$access_token = $this->getWxAccessToken();
		$url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
		$postArr=array(
			'button'=>array(
				array(
					"type"=>'click',
					"name"=>'电影',
					"key"=>'sdfasf'
				),
				array(
					"name"=>'菜单',
					"sub_button"=>array(
						array(
							'type'=>'view',
							'name'=>'游戏1',
							'url'=>'http://www.zhengchaolong.cn/index.php/Home/Index/game1'
						),
						array(
							'type'=>'view',
							'name'=>'游戏2',
							'url'=>'http://www.zhengchaolong.cn/index.php/Home/Index/game2'
						)
					),
				),
			),
		);
		//$postJson = urldecode(json_encode($postArr)); 不知道为什么不成功
		$postJson = json_encode($postArr,JSON_UNESCAPED_UNICODE);
		echo $postJson;
		$res = $this->http_curl($url,'post','json',$postJson);
		var_dump($res);
	}

//获取用户的openid
	// function getBaseInfo(){
	// 	$appid = "wx486c0d836824ac89";
	// 	//自动回调到下一个方法，注意这里的域名要和网页账号授权获取信息的域名一致
	// 	$redirect_uri = urlencode("http://www.zhengchaolong.cn/index.php/Home/Index/getUserOpenId");
	// 	$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
	// 	header('location:'.$url);
	// }

	// function getUserOpenId(){
	// 	$appid = "wx486c0d836824ac89";
	// 	$appsecret = "23224a1ca9cedf520cfade68118f1443";
	// 	$code = $_GET['code'];
	// 	$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
	// 	$res = $this->http_curl($url,'get');
	// 	var_dump($res);
	// 	//进来一次写一次数据库，判断活动的剩余次数；
	// 	//$this->display('index');
	// }

//获取用户的详细信息
	// function getUserDetail(){
	// 	$appid = "wx486c0d836824ac89";
	// 	//自动回调到下一个方法，注意这里的域名要和网页账号授权获取信息的域名一致
	// 	$redirect_uri = urlencode("http://www.zhengchaolong.cn/index.php/Home/Index/getUserInfo");
	// 	$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
	// 	header('location:'.$url);
	// }

	// function getUserInfo(){
	// 	//网页授权
	// 	$appid = "wx486c0d836824ac89";
	// 	$appsecret = "23224a1ca9cedf520cfade68118f1443";
	// 	$code = $_GET['code'];
	// 	$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
	// 	$res = $this->http_curl($url,'get');
	// 	//获取网页的access_token , openid
	// 	$access_token=$res['access_token'];
	// 	$openid = $res['openid'];
	// 	$url="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
	// 	$res = $this->http_curl($url,'get');
	// 	var_dump($res);
	// }

	

	// public function getJsApiTicket(){
	// 	if($_SESSION['jsapi_ticket_expire_time']>time() && $_SESSION['jsapi_ticket'] ){
	// 		return $_SESSION['jsapi_ticket'];
	// 	}else{
	// 		$access_token = $this->getWxAccessToken();
	// 		$url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi";
	// 		$res = $this->http_curl($url,'get');
	// 		$jsapi_ticket = $res['ticket'];
	// 		$_SESSION['jsapi_ticket'] = $jsapi_ticket;
	// 		$_SESSION['jsapi_ticket_expire_time'] = time()+7000;
	// 		return $jsapi_ticket;
	// 	}
		
	// }

	// public function	getRandCode(){
	// 	$array=array(
	// 		'a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c',
	// 		'a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c','a','b','c',
	// 	);
	// 	$tmpstr = "";
	// 	$max = count($array);
	// 	for($i=1;$i<=16;$i++){
	// 		$key=rand(0,$max-1);
	// 		$tmpstr .= $array[$key];
	// 	}
	// 	return $tmpstr;
	// }

	// public function shareWx(){
	// 	//获取jsapi_ticket
	// 	$jsapi_ticket = $this->getJsApiTicket();
	// 	$timestamp = time();
	// 	$nonceStr=$this->getRandCode();
	// 	$url = 'http://www.zhengchaolong.cn/index.php/Home/Index/shareWx';
	// 	$signature="jsapi_ticket=".$jsapi_ticket."&noncestr=".$nonceStr."&timestamp=".$timestamp."&url=".$url;
	// 	$signature = sha1($signature);

	// 	$this->assign('name','chao');
	// 	$this->assign('timestamp',$timestamp);
	// 	$this->assign('nonceStr',$nonceStr);
	// 	$this->assign('signature',$signature);
	// 	$this->display('share');

	// }


	

}